package fastwave.cloud.demo.fastwave.biz.publisher.controller;

import com.alibaba.fastjson.JSON;
import fastwave.cloud.demo.fastwave.biz.publisher.domain.MsgLog;
import fastwave.cloud.demo.fastwave.biz.publisher.service.MsgLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * <p>Title: AmqpController</p>
 * <p>Description: </p>
 *
 * @author: dwLiu
 * @date: 2020/4/6 23:46
 */
@RestController
@RequestMapping("ampq")
public class AmqpController {

    private static Logger logger = LoggerFactory.getLogger(AmqpController.class);
    @Autowired
    private MsgLogService msgLogService;
    @Resource
    RabbitTemplate template;

    @Resource(name = "TemplateReliable")
    RabbitTemplate rabbitTemplate;

    @GetMapping(value = "/reliable")
    public String reliable(@RequestParam Map<String, Object> params) {
        try {
            String msg = JSON.toJSONString(params);
            String uuid = UUID.randomUUID().toString();
            Date curTime = new Date();
            MsgLog msgLog = new MsgLog();
            msgLog.setMsgId(uuid);
            msgLog.setStatus(-1);
            msgLog.setExchange("EmailExchange");
            msgLog.setMsg(msg);
            msgLog.setTryCount(0);
            msgLog.setRoutingKey("EmailRouting");
            msgLog.setCreateTime(curTime);
            msgLog.setUpdateTime(curTime);
            msgLog.setNextTryTime(curTime);
            msgLogService.save(msgLog);
            Message message = MessageBuilder.withBody(msg.getBytes()).setMessageId(uuid).build();
            rabbitTemplate.convertAndSend("EmailExchange", "EmailRouting", message,new CorrelationData(uuid));
            return "已成功发送到broker";
        } catch (AmqpException e) {
            logger.error(e.getMessage());
            return "出现异常，请稍后再试";
        }
    }

    @GetMapping(value = "/direct")
    public String sendMsg(@RequestParam Map<String, Object> params) {
        try {
            String msg = params.get("msg").toString();
            template.convertAndSend("EmailExchange", "EmailRouting", msg);
            return "OK";
        } catch (AmqpException e) {
            return "网络异常";
        }
    }

    /**
     * 没有交换机的时候，也会走OK,可以自己定义Template,不能用RabbitTemplate
     *
     * @param params
     * @return
     */
    @GetMapping(value = "/noExchange")
    public String noExchange(@RequestParam Map<String, Object> params) {
        try {
            String msg = params.get("msg").toString();
//            template.convertAndSend("noExchange", "EmailRouting", msg);
//            template.convertAndSend("EmailExchange", "EmailRouting2", msg);
            String uuid = UUID.randomUUID().toString();
            template.convertAndSend("EmailExchange", "EmailRouting2", msg, new CorrelationData(uuid));
            return "OK";
        } catch (AmqpException e) {
            return "网络异常";
        }
    }

    @GetMapping(value = "/topic")
    public String sendBlog(@RequestParam Map<String, Object> params) {
        String msg = params.get("msg").toString();
        String routingKey = params.get("key").toString();
        template.convertAndSend("BlogExchange", routingKey, msg);
        return "OK";
    }

    @GetMapping(value = "/fanout")
    public String sendFanout(@RequestParam Map<String, Object> params) {
        String msg = params.get("msg").toString();
        template.convertAndSend("FanoutExchange", null, msg);
        return "OK";
    }

    @GetMapping(value = "/header")
    public String sendHeader(@RequestParam Map<String, Object> params) {
        String msg = params.get("msg").toString();
        MessageProperties messageProperties = new MessageProperties();
        if (params.get("token") != null) {
            messageProperties.setHeader("token", params.get("token").toString());
        }
        if (params.get("id") != null) {
            messageProperties.setHeader("id", params.get("id").toString());
        }
        Message message = new Message(msg.getBytes(), messageProperties);
        template.convertAndSend("HeadersExchange", null, message);
        return "OK";
    }
}
